package com.alibaba.nacos.naming.push.v2;

import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.MultiSubscriber;
import com.alibaba.nacos.naming.core.v2.event.publisher.NamingEventPublisherFactory;
import com.alibaba.nacos.naming.core.v2.event.service.ServiceEvent;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.push.NamingSubscriberService;
import com.alibaba.nacos.naming.push.v2.task.PushDelayTask;
import com.alibaba.nacos.naming.push.v2.task.PushDelayTaskExecuteEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class NamingSubscriberServiceV2Impl
        extends MultiSubscriber
        implements NamingSubscriberService {

    @Autowired
    private PushDelayTaskExecuteEngine pushDelayTaskExecuteEngine;

    @PostConstruct
    public void init() {
        NotifyCenter.registerSubscriber(this, NamingEventPublisherFactory.INSTANCE);
    }

    @Override
    public List<Class<? extends Event>> subscribeTypes() {
        return List.of(ServiceEvent.ServiceChangedEvent.class, ServiceEvent.ServiceSubscribedEvent.class);
    }

    @Override
    public void onEvent(Event event) {
        if (event instanceof ServiceEvent.ServiceChangedEvent serviceChangedEvent) {
            Service service = serviceChangedEvent.getService();
            pushDelayTaskExecuteEngine.addTask(service, new PushDelayTask(service, 500L));
            return;
        }

        if (event instanceof ServiceEvent.ServiceSubscribedEvent serviceSubscribedEvent) {
            Service service = serviceSubscribedEvent.getService();
            pushDelayTaskExecuteEngine.addTask(service, new PushDelayTask(service, 500L, serviceSubscribedEvent.getClientId()));
            return;
        }

        throw new UnsupportedOperationException();
    }
}
